#include <gtest/gtest.h>
#include <atomic>
#include <chrono>
#include <thread>

#include "Thread.h"

// 验证线程会执行传入的回调
TEST(ThreadTest, ExecutesCallable) {
  std::atomic_int counter{0};

  Thread worker([&] {
    counter.fetch_add(1, std::memory_order_relaxed);
  });

  worker.start();
  worker.join();

  EXPECT_EQ(counter.load(std::memory_order_relaxed), 1);
}

// 验证重复 start() 会抛出异常
TEST(ThreadTest, StartTwiceThrowsLogicError) {
  Thread worker([] { /* no-op */ });

  worker.start();
  EXPECT_THROW(worker.start(), std::logic_error);

  worker.join();
}

// 验证析构函数会自动 join
TEST(ThreadTest, DestructorJoinsThreadAutomatically) {
  std::atomic_bool ran{false};

  {
    Thread worker([&] {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      ran.store(true, std::memory_order_relaxed);
    });
    worker.start();
    // 离开作用域将触发析构，析构函数会先 join
  }

  EXPECT_TRUE(ran.load(std::memory_order_relaxed));
}